<template>
    <div class="file-load" :data-required="required">
        <el-tooltip class="box-item" effect="dark" :content="fileName || placeholder" placement="top">
            <div class="file-name" :data-file="!!fileName">
                <p class="mouse-active" @click="downloadHistory">{{ fileName || placeholder }}</p>
                <i class="icon-del mouse-active" @click="del" v-if="!!fileName && !disabled"></i>
            </div>
        </el-tooltip>
        <div class="btns">
            <el-button :data-font="$i18n.locale" class="upload-btn" @click="downloadExcel"
                v-if="!!telplates && !disabled">{{
                    $t('application.form.download')
                }}</el-button>
            <el-button :data-font="$i18n.locale" class="upload-btn" @click="getFile" v-if="!fileName && !disabled">{{
                $t('application.form.upload')
            }}</el-button>
        </div>
        <input type="file" ref="file" :accept="accept" style="display: none;" @change="handleFileUpload($event)">
    </div>
</template>

<script>
import axios from "axios"
import Confirm from '@/components/message/confirm.js'
import { OSSPolicy } from "@/request/api"
export default {
    props: {
        placeholder: {
            type: String,
            default: "请上传文件"
        },
        required: {
            type: Boolean,
            default: false
        },
        accept: {
            type: String,
            default: ""
        },
        size: {
            type: [String, Number],
            default: ''
        },
        history: {
            type: String,
            default: ""
        },
        telplates: {
            type: String,
            default: ""
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            fileName: !!this.history ? '点击下载历史文件' : '',
            fileUrl: this.history
        }
    },
    methods: {
        del() {
            if (this.$i18n.locale === 'zh') {
                Confirm({ title: '删除项目', message: '确定要删除该附件吗？', left: '取消', right: '删除' })
                    .then(() => {
                        this.fileName = "";
                        this.$refs.file.value = "";
                        this.fileUrl = "";
                    })
                    .then((ret) => {

                    })
                    .catch((err) => {
                        // 点击取消按钮触发
                        if (err === 'cancel') return
                    })
            } else {
                Confirm({ title: 'Delete Item', message: 'Are you sure you want to delete this attachment?', left: 'Cancel', right: 'Delete' })
                    .then(() => {
                        this.fileName = "";
                        this.$refs.file.value = "";
                        this.fileUrl = "";
                    })
                    .then((ret) => {

                    })
                    .catch((err) => {
                        // 点击取消按钮触发
                        if (err === 'cancel') return
                    })
            }

        },
        downloadExcel() {
            const element = document.createElement('a')
            element.setAttribute('href', this.telplates)
            element.setAttribute('target', '_blank')
            element.style.display = 'none'
            element.click();
        },
        downloadHistory() {
            if (this.fileUrl) {
                const element = document.createElement('a')
                element.setAttribute('href', this.fileUrl)
                element.setAttribute('target', '_blank')
                element.style.display = 'none'
                element.click();
            }
        },
        // 打开文件
        getFile() {
            this.$refs.file.click()
        },
        // 获取文件
        handleFileUpload(event) {
            // 阻止发生默认行为
            event.preventDefault();
            let file = this.$refs.file.files[0]
            if (!file) {
                return
            }
            console.log(file);
            if (this.getCode(file) === -1) {
                this.$toast('文件类型不正确', 2000, 'warning');
                this.$refs.file.value = "";
                return;
            } else if (this.getCode(file) === -2) {
                this.$toast('文件体积过大', 2000, 'warning');
                this.$refs.file.value = "";
                return;
            } else {
                this.fileName = file.name
                this.onUpload(file)
            }

        },
        // 上传文件
        async onUpload(file) {
            let res = await OSSPolicy();
            let keys = res.data.data.dir + '/' + this.getUUID() + `_${file.name}`;
            axios({
                url: res.data.data.host,
                headers: {
                    'content-type': 'multipart/form-data'
                },
                method: "post",
                data: {
                    key: keys,
                    policy: res.data.data.policy,
                    signature: res.data.data.signature,
                    ossaccessKeyId: res.data.data.accessKeyId,
                    dir: res.data.data.dir,
                    file: file,
                    host: res.data.data.host,
                    callback: res.data.data.callback,
                    success_action_status: "200"
                },
            }).then(res1 => {
                console.log(res1);
                if (res1.status == "200") {
                    this.$emit('message', res.data.data.host + '/' + keys)
                    this.fileUrl = res.data.data.host + '/' + keys
                }
            }).catch(err => {
                this.fileName = "";
                this.$refs.file.value = "";
                this.fileUrl = "";
                this.$toast('上传失败', 2000, 'error');
            })

        },
        getCode(file) {
            if (this.accept) {
                let type = false;
                let str = this.accept.split(".").join("")
                str.split(',').forEach(item => {
                    if (item === file.name.split('.')[file.name.split('.').length - 1]) {
                        type = true
                    }
                })
                if (type === false) {
                    return -1
                }

            }
            if (this.size && (this.size * 1024 * 1024) < file.size) {
                return -2
            }
        },
        getUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
                return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
            })
        },
    },
    watch: {
        history: {
            deep: true,
            handler(newVal, oldVal) {
                this.fileName = "点击下载历史文件"
                this.$emit('message', newVal)
                this.fileUrl = newVal
            },
        },
        fileUrl: {
            deep: true,
            handler(newVal, oldVal) {
                this.$emit('message', newVal)
            },
            immediate: true
        }
    }
}
</script>

<style lang="less" scoped>
.file-load {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
}

.file-load[data-required=true]::before {
    content: '*';
    font-size: 0.53rem;
    font-family: 'IdeaFonts-DianHei-EEJ', 'IdeaFonts-DianHei';
    font-weight: normal;
    color: #F64F4F;
    line-height: 0.85rem;
    position: absolute;
    left: -0.27rem;
    top: 50%;
    transform: translateY(-50%);
}

.btns {
    display: flex;
    align-items: center;
}

.upload-btn {
    width: auto;
    height: auto;
    margin-right: 0.11rem;
    margin-left: 0;
    padding: 0.03rem 0.21rem;
    background: linear-gradient(315deg, rgba(250, 251, 255, 0.25) 0%, rgba(252, 248, 255, 0.25) 100%);
    border-radius: 0.11rem;
    border: 0.03rem solid #7709CC;
    backdrop-filter: blur(10px);

    :deep(span) {
        font-size: 0.37rem;
        color: #7709CC;
        line-height: 0.59rem;
    }
}

.upload-btn[data-font='zh'] {
    :deep(span) {
        font-family: 'IdeaFonts-DianHei-CEJ', 'IdeaFonts-DianHei';
        font-weight: normal;
    }
}

.upload-btn[data-font='en'] {
    :deep(span) {
        font-weight: 300;
        font-family: 'Helvetica-Light, Helvetica';
    }
}

.file-name {
    height: 0.85rem;
    position: relative;
    width: max-content;
    max-width: 70%;
    padding-right: 0.32rem;

    p {
        font-size: 0.53rem;
        font-family: 'IdeaFonts-DianHei-DEJ', 'IdeaFonts-DianHei';
        font-weight: normal;
        color: #C5C5CA;
        line-height: 0.85rem;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 1; // 控制多行的行数
        -webkit-box-orient: vertical;
    }
}

.file-name[data-file=true] {
    p {
        color: #68656C !important;
    }
}


.icon-del {
    width: 0.64rem;
    height: 0.64rem;
    background: url('@/assets/img/application/delete.png') no-repeat;
    background-size: 0.32rem 0.32rem;
    background-position: 50% 50%;
    position: absolute;
    right: -0.45rem;
    top: 0.32rem;
    transform: translateY(-50%);
}
</style>